using System;
using Lichtspiel.ECSystem.Behaviors;
using Lichtspiel.Math;
using Lichtspiel.Utility;

namespace Lichtspiel.ECSystem.Actions
{
    public class ScaleTo : Behavior
    {
        private TimeSpan length;
        private Interpolator<Vector2>.InterpolationMethod interpMethod;
        private Interpolator<Vector2> interpolator;
        private Vector2 start;
        private Vector2 target;

        public ScaleTo(Vector2 target, TimeSpan length)
            : this(target, length, InterpolationHelper.Linear) { }

        public ScaleTo(Vector2 target, TimeSpan length, Action finished)
            : this(target, length, InterpolationHelper.Linear, finished) { }

        public ScaleTo(Vector2 target, TimeSpan length, Interpolator<Vector2>.InterpolationMethod interpMethod)
            : this(target, length, interpMethod, null) {}

        public ScaleTo(Vector2 target, TimeSpan length, Interpolator<Vector2>.InterpolationMethod interpMethod, Action finished)
            : base(finished) {
            this.length = length;
            this.target = target;
            this.interpMethod = interpMethod;
        }

        protected override void Initialize() {
            start = owner.Scale;

            interpolator = new Interpolator<Vector2>(start, target, length, interpMethod, i => owner.Scale = i.Value,
                                                     i => BehaviorFinished());
        }

        public override void Update(GameTime time) {
            base.Update(time);

            interpolator.Update(time);
        }

        internal override void Stop() {
            base.Stop();

            interpMethod = null;
            if (interpolator != null) {
                interpolator.Stop();
            }
            interpolator = null;
        }
    }
}